﻿using Microsoft.AspNetCore.Mvc;
using MyBlog.WebApi.Models;
using MyBlog.WebApi.Models.DTOs;
using MyBlog.WebApi.Models.ViewModels;
using MyBlog.WebApi.Services.Interfaces;

namespace MyBlog.WebApi.Controllers
{
    /// <summary>
    /// 创建API控制器，用于处理博客文章相关的请求
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class BlogPostsController : ControllerBase
    {
        private readonly IBlogPostService _blogPostService;

        public BlogPostsController(IBlogPostService blogPostService)
        {
            _blogPostService = blogPostService;
        }

        [HttpGet]
        public async Task<ActionResult<PagedResult<BlogPost>>> GetPosts([FromQuery] BlogQueryParameter parameter)
        {
            var result = await _blogPostService.GetPagedPostsAsync(parameter);
            return Ok(result);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<BlogPost>> GetPost(int id)
        {
            var post = await _blogPostService.GetPostByIdAsync(id);
            if (post == null) return NotFound();
            return Ok(post);
        }

        [HttpPost]
        public async Task<ActionResult<int>> CreatePost(CreateBlogPostDto dto)
        {
            var postId = await _blogPostService.CreatePostAsync(dto);
            return CreatedAtAction(nameof(GetPost), new { id = postId }, postId);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdatePost(int id, UpdateBlogPostDto dto)
        {
            dto.Id = id;
            var success = await _blogPostService.UpdatePostAsync(dto);
            if (!success) return NotFound();
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePost(int id)
        {
            var success = await _blogPostService.DeletePostAsync(id);
            if (!success) return NotFound();
            return NoContent();
        }
    }
}
